import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gistmap.bean.User;



/**
 * 过滤认证流程
 * @author Administrator
 *
 */
public class AuthorityFilter implements Filter{
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }


    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        //csdn普通无法登录，但是下载csdn资源的时候，要求我必须先登陆
        //天猫、京东我浏览商品无序登录，当我加入购物车或者支付才要求必须先登录
        //jsp、servelet
        //login.jsp LoginServlet.do---登录流程明显不需要过滤器，其他的都给我使用过滤器
        //.js .css 图片都不需要认证

        //如果不需要认证的资源直接按原有流程执行---直接放行
        //如果需要认证的资源 必须先检查是否已经正常登录  Y--直接放行， N---提示登录
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        HttpServletResponse httpResponse = (HttpServletResponse)response;

        System.out.println("URI:" + httpRequest.getRequestURI());
        System.out.println("URL:" + httpRequest.getRequestURL());
        String uri = httpRequest.getRequestURI();
        if (uri.contains("login")|| uri.contains("prompt") || uri.contains("main") || uri.contains("register") || uri.contains("main.jsp"))
        {
            //直接放行
            chain.doFilter(httpRequest, httpResponse);
        }
        else{
            //过滤如果没有登录，要求登录
            User userLogin = (User)httpRequest.getSession().getAttribute("user");
            if (null  != userLogin){
                chain.doFilter(httpRequest, httpResponse);
            }else{
                System.out.println(uri);
                httpResponse.sendRedirect(httpRequest.getContextPath() + "/" + "jsp/prompt.jsp");
            }
        }
    }


    public void destroy() {
        // TODO Auto-generated method stub

    }
}
